package com.eric.downloader;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.concurrent.LinkedBlockingQueue;

import org.apache.http.HttpHost;

public class MyProxy{
		
	HttpHost httpProxy;
	
	String fileLoc;
	
	private static LinkedBlockingQueue<HttpHost> httpProxyQueue = new LinkedBlockingQueue<>();	

//	private static LinkedBlockingQueue<Entry<String,String>> queue = new LinkedBlockingQueue<>();
	
	//Constructor add initial proxy
	public MyProxy () {
		add("121.10.240.45","80");
	}
	
	public int size() {
		return httpProxyQueue.size();
	}
	
	public HttpHost poll () {
		if (httpProxyQueue.size() < 2) loadProxy(fileLoc);
		return httpProxyQueue.poll();
	}
	
	public void add (String proxy,String port,String type) {
		httpProxyQueue.add(new HttpHost(proxy,Integer.parseInt(port),type));
	}
	
	public void add (String proxy,String port) {
		httpProxyQueue.add(new HttpHost(proxy,Integer.parseInt(port),"http"));
//		queue.addAll(map.entrySet());
	}
	
	public LinkedBlockingQueue<HttpHost> loadProxy (String fileLoc) {
		this.fileLoc = fileLoc;
		try {
			BufferedReader br = new BufferedReader(new FileReader(new File(fileLoc)));
			
			String line;
			while ((line=br.readLine()) != null) {
				String h = line.split(":")[0];
				String p = line.split(":")[1];
				httpProxyQueue.add(new HttpHost(h,Integer.parseInt(p),"http"));
			}
			br.close();
//			queue.addAll(map.entrySet());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return httpProxyQueue;
	}

}
